﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using BLL;
using DAL;
using DAL.Dao;
using ExpressManagement.Areas.BackSys.ServiceTools;
using DAL.Models;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Mvc;
using AutoMapper;
using Microsoft.Extensions.Caching.Memory;
using BLL.Interface;
using ExpressManagement.Areas.BackSys.ServiceTools.Redis;
using Microsoft.EntityFrameworkCore;
using DAL.Models.DTO;

namespace ExpressManagement.Areas.BackSys.Controllers
{
    [Area("BackSys")]
    //[Route("api/[controller]")]
    //[ApiController]
    public class ManagerController : BaseController
    {

        // GET: Manager
        private readonly IManagerImpl _impl;

        public ManagerController(IMemoryCache _memoryCache, IManagerImpl _impl, RedisHelper redisHelper, ExpressDBContext _dbContext, IHttpContextAccessor httpContextAccessor, DbContextOptions<ExpressDBContext> _dbContextoptions, IMapper mapper, SignalRSender signalRSender)
            : base(mapper: mapper, signalRSender: signalRSender, httpContextAccessor: httpContextAccessor, _memoryCache: _memoryCache, redisHelper: redisHelper, _dbContext: _dbContext, dbContextOptions: _dbContextoptions)

        {
            //if (_impl == null) _impl = new ManagerImpl();
            this._impl = _impl;
        }

        public async Task<IActionResult> ManagerRegister()
        {

            switch (LoginType)
            {
                case "用户":
                    return RedirectToAction("Index", "Home");
                case "管理员":
                case "快递员":
                    return PartialView(_impl.GetList());
                default:
                    break;
            }

            return PartialView(_impl.GetList());
        }



        public async Task<IActionResult> ManagerManage()
        {
            return PartialView();
        }

        // POST: /BackSys/Manager/Create
        [HttpGet]
        //[ResponseCache(Duration = 10)]
        public async Task<IActionResult> GetItemByID([FromQuery]int id, [FromQuery]string action)
        {
            var result = _impl.GetItemByID(Convert.ToInt32(id));
            string seri = JsonConvert.SerializeObject(result);
            return Json(seri);
        }



        [HttpPost]
        public async Task<IActionResult> Add([FromForm] ManagerDTO entity)
        {
            Manager manager = _mapper.Map<Manager>(entity);
            //manager.UserName = Request.Form["UserName"];
            //manager.UserPass = Request.Form["UserPass"];
            //manager.Phone = Request.Form["Phone"];
            //manager.TrueName = Request.Form["TrueName"];
            //manager.Idcard = Request.Form["Idcard"];
            manager.AddTime = DateTime.Now;
            if (_impl.Add(manager) == true) return Json(1);
            return Json(0);
        }



        [HttpGet]
        //[ResponseCache(Duration = 10)]
        public async Task<IActionResult> ChangePage([FromQuery]int page)
        {
            string keyStr = string.Empty;
            string cache = string.Empty;
            string serializeStr = string.Empty;
            IDictionary<string, string> set = new Dictionary<string, string>();
            //MySession.WriteSession("managerPage",page);
            int? rows = GetInt32FromSession("managerRows");
            keyStr = string.Format("{0},{1},{2}", LoginType, "Manager", page);
            cache = GetCacheFromRedis<string>(EntityManager, TypePage, page, LoginType);
            if (!string.IsNullOrEmpty(cache))
            {
                return Json(cache);
            }
            else
            {
                (var totalPages, var data) = _impl.GetList(rows.Value, page);
                FillSetAndSaveCache(totalPages, JsonConvert.SerializeObject(data), page, set, EntityManager, TypePage, LoginType, out serializeStr);
                return Json(serializeStr);
            }


        }


        [HttpPost]
        public async Task<IActionResult> Update([FromForm]ManagerDTO entity)
        {
            Manager manager = _mapper.Map<Manager>(entity);
            //manager.Id = Convert.ToInt32(Request.Form["Id"]);
            //manager.UserName = Request.Form["UserName"];
            //manager.UserPass = Request.Form["UserPass"];
            //manager.Phone = Request.Form["Phone"];
            //manager.TrueName = Request.Form["TrueName"];
            //manager.Idcard = Request.Form["Idcard"];
            manager.UpdateTime = DateTime.Now;
            if (_impl.Update(manager.Id, manager))
            {
                RemoveRedisCacheEntity(EntityManager, TypePage, LoginType);
                return Json(1);
            }
            return Json(0);
        }
        //


        [HttpPost]
        public async Task<IActionResult> Delete()
        {
            int id = 0;
            if (int.TryParse(Request.Form["Id"], out id) && _impl.Delete(id) == true)
            {
                RemoveRedisCacheEntity(EntityManager, TypePage, LoginType);
                return Json(1);
            }
            return Json(0);
        }

    }
}